import { Tabs,Button,Form, Modal,message,Row,Col } from 'antd';
import PropTypes from 'react-router/lib/PropTypes';
const TabPane = Tabs.TabPane;
const createForm = Form.create;
const FormItem = Form.Item;
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import cloneDeep from 'lodash/cloneDeep'
import forEach from 'lodash/forEach'
import Immutable from 'immutable'
const is = Immutable.is;

import * as MyCardAction from '../../actions/myCard'
import { WeaErrorPage, WeaTools,WeaSearchBrowserBox,WeaTableEdit,WeaSearchGroup,WeaRightMenu} from 'ecCom'
import TopButton from '../public/topButton';
import {getParamsByConditions, formatFieldsByParams} from '../../utils'

class PersonInfo extends React.Component {
    static contextTypes = {
        router: PropTypes.routerShape,
    }
    constructor(props) {
        super(props);
        const funcs = ['tableEditChange', 'onRightMenuClick', 'editCard','backCard','saveEditCard', 'onTabChange'];
        funcs.forEach(f=> this[f] = this[f].bind(this))
        this.state={
            conditionInfo: [],
            tableInfo: [],
            isEditor: false,
            buttons: {},
        }
    }
    componentDidMount(){
        this.init();
    }
    init(cb) {
        const hrmId = this.props.params.hrmId || '';
        WeaTools.callApi('/api/hrm/resource/getResourceCard','GET',
            {operation:'getResourcePesonalView', id:hrmId})
        .then((data)=> {
            this.conditionInfoBK = cloneDeep(data.result.conditions);
            this.tableInfoBK = cloneDeep(data.result.tables);
            this.setState({conditionInfo: data.result.conditions, tableInfo: data.result.tables, buttons: data.result.buttons});
            cb && cb();
        })
    }
    shouldComponentUpdate(nextProps, nextState) {
        return true
    }
    componentWillUnmount() {
        const {actions} = this.props;
        actions.saveFormFields();
    }
    getTabChildren(){
        const {tableInfo, isEditor} = this.state;
        let tabChildren = [];
        tableInfo && tableInfo.map((t,i)=>{
            tabChildren.push(
                <TabPane tab={t.tabname} key={i}>
                    <WeaTableEdit
                        columns={t.tabinfo.columns}
                        datas={t.tabinfo.datas}
                        onChange={this.tableEditChange}
                        viewAttr={isEditor?2: 1}
                    />
                </TabPane>
            );
        })
        return tabChildren;
    }
    getSearchs(){
        const {conditionInfo, isEditor} = this.state;
        let group = [];
        conditionInfo && conditionInfo.forEach(c =>{
            let items = [];
            c.items.forEach( field => {
                items.push({
                    com:(<FormItem
                        label={`${field.label}`}
                        labelCol={{span: `${field.labelcol}`}}
                        wrapperCol={{span: `${field.fieldcol}`}}>
                            {WeaTools.getComponent(
                                field.conditionType,field.browserConditionParam,field.domkey,this.props,field,!isEditor
                            )}
                        </FormItem>),
                    colSpan: 1
                });
            });
            group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
        });
        return group;
    }
    tableEditChange(data){
        const key = this.state.tabkey || 0;
        let tableInfo = cloneDeep(this.state.tableInfo);
        tableInfo[key].tabinfo.datas = data;
        this.setState({tableInfo});
    }
    onTabChange(key) {
        this.setState({tabkey: key});
    }
    getRightMenu(){
        const {isEditor} = this.state;
        let arr = [];
        if (isEditor){
            arr = [{
                icon: <i className='icon-coms-ws'/>,
                content:'保存'
            }, {
                icon: <i className='icon-coms-ws'/>,
                content:'返回'
            }
            ]
        } else {
            arr = [{
                    icon: <i className='icon-coms-ws'/>,
                    content:'编辑'
                }
            ]
        }
        return arr;
    }
    onRightMenuClick(key){
        const {isEditor} = this.state;
        if (isEditor) {
            switch(key){
                case '0':
                    this.saveEditCard();
                    break;
                case '1':
                    this.backCard();
                    break;
            }
        } else {
            switch(key){
                case '0':
                    this.editCard();
                    break;
            }
        }
    }
    getTopButtons() {
        const {isEditor, buttons} = this.state;
        const save = <Button type="primary" disabled={false} onClick={this.saveEditCard} >保存</Button>;
        const back = <Button disabled={false} onClick={this.backCard} >返回</Button>;
        const edit = <Button type="primary" disabled={false} onClick={this.editCard} >编辑</Button>;
        const btns = [];
        if (isEditor) {
            if (buttons.hasSave) {
                btns.push(save);
                btns.push(back);
            }
        } else {
            if (buttons.hasEdit) {
                btns.push(edit);
            }
        }
        return btns;
    }
    editCard(){
        const {actions} = this.props;
        let conditionInfo = cloneDeep(this.state.conditionInfo);
        let tableInfo = cloneDeep(this.state.tableInfo);
        conditionInfo && conditionInfo.forEach(c =>{
            let items = [];
            c.items.forEach( field => {
                field.viewAttr = 2;
                if (field.conditionType == 'BROWSER') {
                    field.browserConditionParam.viewAttr = 2;
                }
            });
        });
        tableInfo && tableInfo.forEach(t=>{
            t.tabinfo && t.tabinfo.columns && t.tabinfo.columns.forEach(c =>{
                c.com && c.com.forEach(m => {
                    m.viewAttr = 2;
                })
            })
        })
        this.setState({conditionInfo, tableInfo, isEditor:true});
        let params = getParamsByConditions(conditionInfo);
        let field = formatFieldsByParams(params);
        actions.saveFormFields(field);
    }
    saveEditCard(){
        const {actions, params, fieldParams} = this.props;
        const {tableInfo} = this.state;
        const hrmId = params.hrmId;
        let pDatas = {...fieldParams.toJS()};
        tableInfo && tableInfo.forEach(t=>{
            pDatas[t.tabinfo.rownum] = t.tabinfo.datas.length;
            t.tabinfo && t.tabinfo.datas && t.tabinfo.datas.forEach((item, index) =>{
                !isEmpty(item) && forEach(item, (value, key)=> {
                    pDatas[`${key}_${index}`] = value;
                })
            })
        })
        WeaTools.callApi('/api/hrm/resource/editResource','POST',
            {...{operation:'editpersonalinfo', id: hrmId}, ...pDatas}).
        then(data=>{
            if (data.status == '1') {
                message.success('保存成功!');
                actions.saveFormFields();
                this.init(() => {
                    this.setState({isEditor:false});
                });
            } else {
                message.warning(data.message);
            }
        }, error=> {
            message.warning(error.message);
        })
    }
    backCard(){
        const {actions} = this.props;
        this.setState({isEditor:false, tableInfo: this.tableInfoBK, conditionInfo: this.conditionInfoBK});
        actions.saveFormFields();
    }
    render() {
        const {actions}=this.props;
        return  (
            <div className='hrm-my-card-personalInfo' style={{height:'100%', position: 'relative'}}>
                <TopButton
                    buttons={this.getTopButtons()}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    onDropMenuClick={this.onRightMenuClick}
                />
                <WeaRightMenu
                    datas={this.getRightMenu()}
                    onClick={this.onRightMenuClick}
                >
                    <Form horizontal>{this.getSearchs()}</Form>
                    <Tabs onChange={this.onTabChange}>{this.getTabChildren()}</Tabs>
                </WeaRightMenu>
            </div>
        )
    }
}

//组件检错机制
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return(
            <WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
        );
    }
}

PersonInfo = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(PersonInfo);

PersonInfo = createForm({
    onFieldsChange(props, fields) {
        props.actions.saveFormFields({...props.fields.toJS(), ...fields});
    },
    mapPropsToFields(props) {
        return props.fields.toJS();
    }
})(PersonInfo);

// 把 state map 到组件的 props 上
const mapStateToProps = state => {
    const {hrmMyCardCore} = state;
    return {
        fields: hrmMyCardCore.get('fields'),
        fieldParams: hrmMyCardCore.get('fieldParams'),
  }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
    return {
        actions: bindActionCreators(MyCardAction, dispatch)
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(PersonInfo);